import React from 'react';
import { connect } from 'dva';

import { withStyles } from '@material-ui/core/styles';

import Button from '@material-ui/core/Button';

import Dialog from '@material-ui/core/Dialog';
import TextField from '@material-ui/core/TextField';
import RightArrowIcon from '@material-ui/icons/KeyboardArrowRight'
import IconButton from '@material-ui/core/IconButton';

import PriceSystemDialog from '../components/PriceSystemDialog';
import Slide from '@material-ui/core/Slide';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import CloseIcon from '@material-ui/icons/Close';
import Input from '@material-ui/core/Input';
import InputLabel from '@material-ui/core/InputLabel';
import InputAdornment from '@material-ui/core/InputAdornment';
import FormControl from '@material-ui/core/FormControl';
import DialogActions from '@material-ui/core/DialogActions';

import MsgBox from '../../../utils/msgbox';
import MsgConfirm from '../../../utils/msgconfirm';

import * as customerService from '../services/customerService';

const styles = {
  appBar: {
    position: 'static',
  },
  flex: {
    flex: 1,
  },
  form: {
    padding: 10,
  },
  menuButton: {
    marginLeft: -12,
    marginRight: 20,
  },
};

function Transition(props) {
  return <Slide direction="up" {...props} />;
}

/**
 * 新建或编辑客户分类
 */
class CategoryEditDialog extends React.Component {
  state = {
    code: '',
    name: '',
    psId: '',
    canDelete: false,
    psDialogOpen: false,
    psName: '[无]',
    msgBoxOpen: false,
    msgBoxInfo: '',
    showEditSuccessDialog: false,
    editInfo: '',
    msgConfirmOpen: false,
    msgConfirmInfo: ''
  }

  onPriceSystemListItemClick = () => {
    this.setState({ psDialogOpen: true });
  }

  onPriceSystemSelect = ({ text, id }) => {
    this.setState({ psName: text, psId: id });
  }

  /**
   * 保存
   */
  onSave = () => {
    const { dispatch, add } = this.props;

    const { id, code, name, psId } = this.state;

    if (!code) {
      this.setState({ msgBoxOpen: true, msgBoxInfo: '没有输入分类编码' });
      return;
    }

    if (!name) {
      this.setState({ msgBoxOpen: true, msgBoxInfo: '没有输入分类名称' });
      return;
    }

    customerService.editCustomerCategory({ id, code, name, psId }).then(
      ({ data: result }) => {
        if (result.success) {
          dispatch({ type: 'customerCategoryList/queryCategoryList', payload: {} });
          this.setState({
            showEditSuccessDialog: true,
            editInfo: add ? '成功新增客户分类' : '成功编辑客户分类',
            id: '', code: '', name: '', psId: '', psName: ''
          });
        } else {
          // 显示错误信息
          this.setState({ msgBoxOpen: true, msgBoxInfo: result.msg });
        }
      }
    );
  }

  /**
   * 删除当前分类
   */
  onDeleteCategory = () => {
    this.setState({
      msgConfirmOpen: true,
      msgConfirmInfo: '请确认是否删除当前分类?'
    });
  }

  doDeleteCategory = () => {
    const { id } = this.state;
    const { dispatch } = this.props;

    customerService.deleteCustomerCategory({ categoryId: id }).then(
      ({ data: result }) => {
        if (result.success) {
          dispatch({ type: 'customerCategoryList/queryCategoryList', payload: {} });
          this.setState({
            showEditSuccessDialog: true,
            editInfo: '成功删除客户分类',
            id: '', code: '', name: '', psId: '', psName: ''
          });
        } else {
          // 显示错误信息
          this.setState({ msgBoxOpen: true, msgBoxInfo: result.msg });
        }
      }
    );
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    const { entity } = nextProps;
    const { id } = prevState;
    if (id !== entity.id) {
      return {
        ...entity
      }
    }
    else {
      return null;
    }
  }

  render() {
    const { classes, entity, open, add, onCancel, onOK, ...other } = this.props;

    const { code, name, psName, canDelete, psDialogOpen, msgBoxOpen, msgBoxInfo,
      showEditSuccessDialog, editInfo, msgConfirmOpen, msgConfirmInfo } = this.state;

    return (
      <Dialog fullScreen open={open} {...other} TransitionComponent={Transition}>
        <AppBar className={classes.appBar}>
          <Toolbar>
            <IconButton className={classes.menuButton} color="inherit" onClick={onCancel}>
              <CloseIcon />
            </IconButton>
            <Typography variant="title" color="inherit" className={classes.flex}>
              {add ? '新增客户分类' : '编辑客户分类'}
            </Typography>
            <Button color="inherit" onClick={this.onSave}>
              保存
            </Button>
          </Toolbar>
        </AppBar>

        <form className={classes.form}>
          <TextField
            id="code"
            label="分类编码"
            margin="normal"
            fullWidth
            required
            type='text'
            value={code}
            onChange={(e) => { this.setState({ code: e.target.value }) }}
          />
          <TextField
            id="name"
            label="分类名称"
            margin="normal"
            fullWidth
            required
            type='text'
            value={name}
            onChange={(e) => { this.setState({ name: e.target.value }) }}
          />
          <FormControl fullWidth margin="normal">
            <InputLabel htmlFor="adornment-password">价格体系</InputLabel>
            <Input onClick={this.onPriceSystemListItemClick} readOnly
              value={psName}
              endAdornment={
                <InputAdornment position="end">
                  <IconButton
                    onClick={this.onPriceSystemListItemClick}
                  >
                    <RightArrowIcon />
                  </IconButton>
                </InputAdornment>
              }
            />
          </FormControl>
        </form>
        {!add && canDelete &&
          <DialogActions>
            <Button onClick={this.onDeleteCategory} color="primary" autoFocus>
              删除当前客户分类
          </Button>
          </DialogActions>
        }
        <PriceSystemDialog open={psDialogOpen}
          onClose={() => { this.setState({ psDialogOpen: false }) }}
          onPriceSystemSelect={this.onPriceSystemSelect} />
        <MsgBox open={msgBoxOpen} info={msgBoxInfo}
          onOK={() => { this.setState({ msgBoxOpen: false, msgBoxInfo: '' }) }} />
        <MsgBox open={showEditSuccessDialog} info={editInfo}
          onOK={() => { this.setState({ showEditSuccessDialog: false, editInfo: '' }); onOK(); }} />
        <MsgConfirm open={msgConfirmOpen} info={msgConfirmInfo}
          onOK={() => {
            this.setState({ msgConfirmOpen: false, msgConfirmInfo: '' });
            this.doDeleteCategory();
          }}
          onCancel={() => { this.setState({ msgConfirmOpen: false, msgConfirmInfo: '' }) }} />
      </Dialog>
    );
  }
}

CategoryEditDialog.propTypes = {
};

function mapStateToProps(state) {
  return {
  };
}

export default connect(mapStateToProps)(withStyles(styles)(CategoryEditDialog));
